<?php

/**
 * quest actions.
 *
 * @package    seth
 * @subpackage quest
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class questActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
    
  public function executeIndex(sfWebRequest $request)
  {
              
        if ($request->isMethod('post')){
  
            $this->getChart=$request->hasParameter("getChart") || $request->hasParameter("getBoth");
            $this->getTable=$request->hasParameter("getTable") || $request->hasParameter("getBoth");
            
            if ($request->hasParameter('kpiDay')){
                
                $this->kpiDayForm=new KpidayReportForm();
                $this->kpiDayForm->bind($request->getParameter('kpiDay'));
                $this->KpiDayDatas=$this->CreateReportKpiDay($request, $this->kpiDayForm);
                $this->getUser()->setAttribute("Datas",$this->KpiDayDatas);
            }
            
            if ($request->hasParameter('srcData')){
                
                $this->srcDataForm=new SourceDataReportForm(null, array("user"=>$this->getUser()));
                $this->srcDataForm->bind($request->getParameter('srcData'));
                $this->srcDatas=$this->CreateReportSrcData($request, $this->srcDataForm);
                $this->getUser()->setAttribute("Datas",$this->srcDatas);
            }
        }
        
        if ($request->isXmlHttpRequest()){
                $this->getUser()->setAttribute("quest_plant", $request->getParameter('plant',null));
                $this->getUser()->setAttribute("quest_powerdev", $request->getParameter('powerdev',null));
        }
        
        if (!isset($this->srcDataForm))
            $this->srcDataForm=new SourceDataReportForm(null, array("user"=>$this->getUser()));
        if (!isset($this->kpiDayForm))
            $this->kpiDayForm=new KpidayReportForm(null, array("user"=>$this->getUser()));

        if ($request->isXmlHttpRequest()){

                $quest=$request->getParameter("quest","kpiDay");
                $form=$quest."Form";
                return $this->renderPartial("quest/".$quest."Form", array("form"=>$this->$form));
        }

  }
  
  public function CreateReportKpiDay(sfWebRequest $request, KpidayReportForm $kpiDayForm){
       
      $this->forward404Unless($request->isMethod('post'));

      if ($kpiDayForm->isValid()){
            
            $plant=array();
            foreach($kpiDayForm->getValue("plant") as $pid){
                $tmp=Doctrine_Core::getTable("Plant")->find($pid);
                if ($tmp->getName()=="All"){
                    unset($plant);
                    $plant=array();
                    $plant=Doctrine_Core::getTable("Plant")->findAll()->getData();
                }else{
                    $plant[]=$tmp;
                }
             }
            
            $range=$kpiDayForm->getValue("date");
            $this->start=new DateTime($range["from"]);
            $this->end=new DateTime($range["to"]);
            
            foreach ($plant as $p){
                  $kpiDatas[$p->getName()]["Daily KPI"]=Doctrine_Core::getTable('kpiday')->getKpiDayByPlant($p, array("start"=>$this->start, "end"=>$this->end,));            
            }
                   
            return $kpiDatas; 
      }
      return null;
  }
  
  public function CreateReportSrcData(sfWebRequest $request, SourceDataReportForm $srcDataForm){
       
      $this->forward404Unless($request->isMethod('post'));

      if ($srcDataForm->isValid()){
          
        $plant=Doctrine_Core::getTable("Plant")->find($srcDataForm->getValue("plant"));
        $range=$srcDataForm->getValue("date");
        $this->start=new DateTime($range["from"]." 00:00");
       
        $this->end=new DateTime($range["to"]." 23:45");
        $vars=$srcDataForm->getValue("variables");

        $devs=array();
        foreach($vars as $var){
            list($plantName, $devLabel, $varName)= explode("-->", $var);
            if (!isset($devs[$devLabel]))
                $devs[$devLabel]=array("Sampletime",$varName);
            else
                $devs[$devLabel][]=$varName;
        } 
        foreach($devs as $devLabel=>$vars){
            $dev=$plant->getPowerDevBy(array("label"=>$devLabel));
            $srcDatas[$plant->getName()][$devLabel]=$dev->getVar(array("vars"=>$vars,"from"=>$this->start,"to"=>$this->end,"noOrder"=>True,"returnArray"=>True));
        }   
        return $srcDatas;  
      }
     
      return null;
  }
  
  public function executeNewMail(sfWebRequest $request){
      
            if ($this->getUser()->hasAttribute("Datas") ){
                   $Datas=$this->getUser()->getAttribute("Datas");
 
                   $this->mailForm=new ReportMailForm(array(
                        "From"=>"Enerqos O&M Services",
                        "Subject"=>"Seth Mail Report",
                   )); 
            }else{
                $this->forward404("Error Preparing Mail Report, please contact the web administrator");

            }
  }
  
  public function executeSendMail(sfWebRequest $request){
      
      $this->forward404Unless($request->isMethod('post'));
      
      $this->mailForm=new ReportMailForm();
      $this->mailForm->bind($request->getParameter("reportMail"));
      
      if ($this->mailForm->isValid()){

            if ($this->getUser()->hasAttribute("Datas") ){
              
              $Datas=$this->getUser()->getAttribute("Datas");
              $body=$this->getPartial("global/sourceDataTable", array("data"=>$Datas));

              if ($this->mailForm->getValue("Text")<>"")
                  $body=$this->mailForm->getValue("Text")." <br><br> ".$body;
             
              
              $msg=$this->getMailer()->compose();
              $msg->setTo(explode(";",$this->mailForm->getValue("To")));
              $msg->setSubject($this->mailForm->getValue("Subject"));
             if ($this->mailForm->getValue("Cc")<>"")
                  $msg->setCc(explode(";",$this->mailForm->getValue("Cc")));
              $msg->setFrom("ing.fulvio.ferrari@gmail.com",$this->mailForm->getValue("From"));
              $msg->setBody($body,"text/html");

              $this->getMailer()->send($msg);
              $this->success=" Mail sent succesfully";
              $this->setTemplate("newMail");
            }else{
                $this->forward404("Error Sending Mail, please try again later");
            }
      }else{
          $this->setTemplate("newMail");
      }
  }
  
  public function executeExportExcel(sfWebRequest $request){
      
       if ($this->getUser()->hasAttribute("Datas") ){
           
            $Datas=$this->getUser()->getAttribute("Datas");
            $labels=sfConfig::get("app_var_label");
            $floats=array("kW","W/mq","kWh","kVarh","°C","m/s","V","A");
            
             //preparing excel fixtures file and forward to download    
            $Excel = new wemPhpExcel();
            $Excel->openWB();

            // Set file properties
            $Excel->activeWB->getProperties()->setTitle("Seth Exported Report");
            $Excel->activeWB->getProperties()->setSubject("Seth Exported Report");
            $Excel->activeSheet->setTitle("Data");

            $startCol=0;
            $startRow=0;
            foreach($Datas as $plant=>$plantData){
                foreach($plantData as $dev=>$devData){
                    
                    $key=0;
                    foreach($devData as $row){
                        $c=$startCol;
                        $r=$startRow+$key+1;
                        
                        foreach($row as $varName=>$val){
                              if ($varName=="id") continue;
                              if ($varName=="plant") continue;
                              if ($varName == 'impen') continue;
 
                              //write labels
                              
                              //prepare labels
                              //replace vars with the configured labels
                              if (key_exists($varName, $labels))
                                $label=$labels[$varName];
                              else
                                $label=$varName;

                              if (strpos($label, "_")!== FALSE){
                                $labelName=substr($label,0, strpos($label, "_"));
                                $um=" [".substr($label,strpos($label, "_")+1)."]";
                               }else{
                                $labelName=$label;
                                $um=NULL;
                               }
                
                              if ($key==0){
                                //Plant label
                                $Excel->activeSheet->setCellValueByColumnAndRow($c,$r,$plant);  
                                //dev label
                                $Excel->activeSheet->setCellValueByColumnAndRow($c,$r+1,$dev);  
                                //var label
                                $Excel->activeSheet->setCellValueByColumnAndRow($c,$r+2,$labelName.$um); 
                              } 
                              $Excel->activeSheet->setCellValueByColumnAndRow($c,$r+3,$val);
                              $c++;
                        }
                        $key++;
                    }
                    $startCol=$c+1;
                }
                
                //Format cells
                $highestCol=$Excel->activeSheet->getHighestColumn();
                for($i=$startRow+1;$i<=$startRow+3;$i++){
                    $Excel->activeSheet->getStyle("A".$i.":".$highestCol.$i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                    $Excel->activeSheet->getStyle("A".$i.":".$highestCol.$i)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
                    $Excel->activeSheet->getStyle("A".$i.":".$highestCol.$i)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $Excel->activeSheet->getStyle("A".$i.":".$highestCol.$i)->getFill()->getStartColor()->setARGB('00680000');            
                }
                
                $startRow=$r+3+1;
                $startCol=0;
            }
            
             $filename="SethReport.xlsx";
             $path=  sfConfig::get("app_temp_data_folder")."/".$filename;
             $Excel->saveWB($path);
             $Excel->closeWB();                   
             $Excel->close();
             unset($Excel);
             
             // Adding the file to the Response object
             $this->getResponse()->clearHttpHeaders();
             $this->getResponse()->setHttpHeader('Pragma: public', true);
             $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename='.$filename);
             $this->getResponse()->setContentType('application/vnd.ms-excel');
             $this->getResponse()->sendHttpHeaders();
             readfile($path);
             return sfView::HEADER_ONLY; 
        }else{
                $this->forward404("Error exporting Report, please contact the web administrator");
            }
  }
}
